﻿#region MIT
/*
Engine Of Evermore (http://code.google.com/p/engineofevermore/)
Copyright (c) 2008, 2009 Michael Woerister

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/
#endregion

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using EngineOfEvermore.Editor.SceneEditor;
using EngineOfEvermore.Scene;
using NUnit.Framework;
using EngineOfEvermore.Common;
using EngineOfEvermore.Scene.Visual;
using EngineOfEvermore.Testing;
using Blue.ResourceManager;
using System.Diagnostics;
using EngineOfEvermore.Imaging;
using NUnit.Mocks;
using System.Drawing;

namespace EngineOfEvermore.Editor.SceneTools
{
    class MouseInputHandler
    {
        public readonly ISelectionHandler SelectionHandler;
        public readonly ISceneGrabber SceneGrabber;
        public readonly ISelectionRectManager VisualManager;
        public readonly IObjectMover ObjectMover;

        private Point _lastMouseDownLocation;
        private InputType _lastEventType;
        private bool _isMouseDown;
        private bool _mouseDownOnSelectedObject;

        public MouseInputHandler( ISelectionHandler selectionHandler, ISceneGrabber grabber,
            ISelectionRectManager visualManager, IObjectMover objectMover )
        {
            Debug.Assert( selectionHandler != null );
            Debug.Assert( grabber != null );
            Debug.Assert( visualManager != null );
            Debug.Assert( objectMover != null );

            this.SelectionHandler = selectionHandler;
            this.SceneGrabber = grabber;
            this.VisualManager = visualManager;
            this.ObjectMover = objectMover;
        }

        public bool CtrlKeyIsPressed { get; set; }
        public bool ShiftKeyIsPressed { get; set; }

        public void HandleInputEvent( MouseEventArgs e, InputType inputType )
        {
            switch ( inputType )
            { 
                case InputType.KeyDown:
                    _handleKeyDownEvent( e );
                    break;

                case InputType.KeyUp:
                    _handleKeyUpEvent( e );
                    break;

                case InputType.MouseMove:
                    _handleMouseMoveEvent( e );
                    break;

                default:
                    break;
            }

            _lastEventType = inputType;
        }

        private void _handleKeyDownEvent( MouseEventArgs e )
        {
            var items = this.SceneGrabber.GetObjectsAtPoint( e.X, e.Y );

            _lastMouseDownLocation = e.Location;
            _isMouseDown = true;
            _mouseDownOnSelectedObject = this.SelectionHandler.Selection.Intersect( items ).Any();
        }

        private void _handleMouseMoveEvent( MouseEventArgs e )
        {
            if ( _isMouseDown )
            {
                if ( !_mouseDownOnSelectedObject )
                {
                    var selectionArea = _getCurrentSelectionArea( e.Location );
                    VisualManager.SelectionRectVisible = true;
                    VisualManager.SetSelectionRect( selectionArea );
                }
                else
                {
                    if ( !this.ObjectMover.IsCurrentlyMovingObjects )
                    {
                        this.ObjectMover.BeginMovingObjects( this.SelectionHandler.Selection,
                            _lastMouseDownLocation );
                    }

                    this.ObjectMover.UpdateObjectPositions( e.Location );
                }
            }
        }

        private void _handleKeyUpEvent( MouseEventArgs e )
        {
            if ( _lastEventType == InputType.KeyDown && _lastMouseDownLocation == e.Location )
            {
                // This is a click
                var sceneObjects = SceneGrabber.GetObjectsAtPoint( e.X, e.Y );
                _setSelectionHandlerMode();
                SelectionHandler.HandlePointSelection( sceneObjects );
            }
            else
            {
                if ( this.ObjectMover.IsCurrentlyMovingObjects )
                {
                    this.ObjectMover.FinishMovingObjects();
                }
                else
                {
                    // This is a drag ;)
                    var selectionArea = _getCurrentSelectionArea( e.Location );

                    var objects = SceneGrabber.GetObjectsInArea( selectionArea );
                    _setSelectionHandlerMode();
                    SelectionHandler.HandleAreaSelection( objects );

                    VisualManager.SelectionRectVisible = false;
                }
            }

            _isMouseDown = false;
            _mouseDownOnSelectedObject = false;
        }

        private void _setSelectionHandlerMode()
        {
            if ( this.ShiftKeyIsPressed && !this.CtrlKeyIsPressed )
            {
                SelectionHandler.Mode = SelectionMode.Add;
            }
            else
                if ( this.CtrlKeyIsPressed )
                {
                    SelectionHandler.Mode = SelectionMode.Toggle;
                }
                else
                {
                    SelectionHandler.Mode = SelectionMode.Single;
                }
        }

        private Rectangle _getCurrentSelectionArea( Point currentCursorPosition )
        {
            int minX = Math.Min( currentCursorPosition.X, _lastMouseDownLocation.X );
            int maxX = Math.Max( currentCursorPosition.X, _lastMouseDownLocation.X );
            int minY = Math.Min( currentCursorPosition.Y, _lastMouseDownLocation.Y );
            int maxY = Math.Max( currentCursorPosition.Y, _lastMouseDownLocation.Y );

            return new Rectangle( minX, minY, maxX - minX + 1, maxY - minY + 1 );
        }

        #if ENGINE_OF_EVERMORE_ENABLE_UNIT_TESTS
        [TestFixture]
        public class Test
        {
            DynamicMock _selectionHandlerMock;
            DynamicMock _grabberMock;
            DynamicMock _visualManagerMock;
            DynamicMock _objectMoverMock;

            [SetUp]
            public void SetUp()
            {
                _selectionHandlerMock = new DynamicMock( "SelectionHandlerMock", 
                    typeof( ISelectionHandler ) );
                _selectionHandlerMock.Strict = true;
                
                _grabberMock = new DynamicMock( "GrabberMock", typeof( ISceneGrabber ) );
                _grabberMock.Strict = true;

                _visualManagerMock = new DynamicMock( "VisualManagerMock", 
                    typeof( ISelectionRectManager ) );
                _visualManagerMock.Strict = true;

                _objectMoverMock = new DynamicMock( "ObjectMoverMock", typeof( IObjectMover ) );
                _objectMoverMock.Strict = true;
            }

            [Test]
            public void TestClickNowhere()
            {
                var clickedObjects = new SceneObject[0];
                _grabberMock.ExpectAndReturn( "GetObjectsAtPoint", clickedObjects, 0, 0 );
                _grabberMock.ExpectAndReturn( "GetObjectsAtPoint", clickedObjects, 0, 0 );

                _selectionHandlerMock.ExpectAndReturn( "get_Selection", new SceneSelection() );
                _selectionHandlerMock.Expect( "set_Mode", SelectionMode.Single ); 
                _selectionHandlerMock.Expect( "HandlePointSelection", 
                    new object[] { clickedObjects } );
                
                MouseInputHandler handler = _createMockedInputHandler();

                var mouseEventArgs = new MouseEventArgs( MouseButtons.Left, 1, 0, 0, 0 );

                handler.HandleInputEvent( mouseEventArgs, InputType.KeyDown );
                handler.HandleInputEvent( mouseEventArgs, InputType.KeyUp );

                _grabberMock.Verify();
                _visualManagerMock.Verify();
                _selectionHandlerMock.Verify();
                _objectMoverMock.Verify();
            }

            [Test]
            public void TestClickOneObject()
            {
                var clickedObjects = new SceneObject[] { new SceneObject() };
                _grabberMock.ExpectAndReturn( "GetObjectsAtPoint", clickedObjects, 0, 0 );
                _grabberMock.ExpectAndReturn( "GetObjectsAtPoint", clickedObjects, 0, 0 );

                _selectionHandlerMock.ExpectAndReturn( "get_Selection", new SceneSelection() );
                _selectionHandlerMock.Expect( "set_Mode", SelectionMode.Single );
                _selectionHandlerMock.Expect( "HandlePointSelection", 
                    new object[]{ clickedObjects } );

                MouseInputHandler handler = _createMockedInputHandler();

                var mouseEventArgs = new MouseEventArgs( MouseButtons.Left, 1, 0, 0, 0 );

                handler.HandleInputEvent( mouseEventArgs, InputType.KeyDown );
                handler.HandleInputEvent( mouseEventArgs, InputType.KeyUp );

                _grabberMock.Verify();
                _visualManagerMock.Verify();
                _selectionHandlerMock.Verify();
                _objectMoverMock.Verify();
            }

            [Test]
            public void TestAreaSelection()
            {
                var clickedObjects = new SceneObject[0];

                _grabberMock.ExpectAndReturn( "GetObjectsAtPoint", clickedObjects, 0, 0 );
                _grabberMock.ExpectAndReturn( "GetObjectsInArea", clickedObjects,
                    new Rectangle( 0, 0, 11, 11 ) );

                _visualManagerMock.Expect( "set_SelectionRectVisible", true );
                _visualManagerMock.Expect( "SetSelectionRect", new Rectangle( 0, 0, 11, 11 ) );
                _visualManagerMock.Expect( "set_SelectionRectVisible", false );

                _selectionHandlerMock.ExpectAndReturn( "get_Selection", new SceneSelection() );
                _selectionHandlerMock.Expect( "set_Mode", SelectionMode.Single );
                _selectionHandlerMock.Expect( "HandleAreaSelection",
                    new object[] { clickedObjects } );

                _objectMoverMock.Strict = false;

                MouseInputHandler handler = _createMockedInputHandler();
                var mouseEventArgsBegin = new MouseEventArgs( MouseButtons.Left, 1, 0, 0, 0 );
                var mouseEventArgsEnd = new MouseEventArgs( MouseButtons.Left, 1, 10, 10, 0 );
                var mouseEventArgsMove = new MouseEventArgs( MouseButtons.None, 0, 10, 10, 0 );

                handler.HandleInputEvent( mouseEventArgsBegin, InputType.KeyDown );
                handler.HandleInputEvent( mouseEventArgsMove, InputType.MouseMove );
                handler.HandleInputEvent( mouseEventArgsEnd, InputType.KeyUp );

                _grabberMock.Verify();
                _visualManagerMock.Verify();
                _selectionHandlerMock.Verify();
                _objectMoverMock.Verify();
            }

            [Test]
            public void TestSwitchingToToggleMode()
            {
                var clickedObjects = new SceneObject[] { new SceneObject() };

                _grabberMock.ExpectAndReturn( "GetObjectsAtPoint", clickedObjects, 0, 0 );
                _grabberMock.ExpectAndReturn( "GetObjectsAtPoint", clickedObjects, 0, 0 );

                _selectionHandlerMock.ExpectAndReturn( "get_Selection", new SceneSelection() );
                _selectionHandlerMock.Expect( "set_Mode", SelectionMode.Toggle );
                _selectionHandlerMock.Expect( "HandlePointSelection",
                    new object[] { clickedObjects } );

                _objectMoverMock.Strict = false;

                var mouseEvent = new MouseEventArgs( MouseButtons.Left, 1, 0, 0, 0 );

                MouseInputHandler handler = _createMockedInputHandler();

                handler.HandleInputEvent( mouseEvent, InputType.KeyDown );
                handler.CtrlKeyIsPressed = true;
                handler.HandleInputEvent( mouseEvent, InputType.KeyUp);

                _grabberMock.Verify();
                _visualManagerMock.Verify();
                _selectionHandlerMock.Verify();
                _objectMoverMock.Verify();
            }

            [Test]
            public void TestSwitchingToToggleModeInAreaSelection()
            {
                var clickedObjects = new SceneObject[0];

                _grabberMock.ExpectAndReturn( "GetObjectsAtPoint", clickedObjects, 0, 0 );
                _grabberMock.ExpectAndReturn( "GetObjectsInArea", clickedObjects,
                    new Rectangle( 0, 0, 11, 11 ) );

                _visualManagerMock.Expect( "set_SelectionRectVisible", true );
                _visualManagerMock.Expect( "SetSelectionRect", new Rectangle( 0, 0, 11, 11 ) );
                _visualManagerMock.Expect( "set_SelectionRectVisible", false );

                _selectionHandlerMock.ExpectAndReturn( "get_Selection", new SceneSelection() );
                _selectionHandlerMock.Expect( "set_Mode", SelectionMode.Toggle );
                _selectionHandlerMock.Expect( "HandleAreaSelection",
                    new object[] { clickedObjects } );

                _objectMoverMock.Strict = false;

                MouseInputHandler handler = _createMockedInputHandler();
                var mouseEventArgsBegin = new MouseEventArgs( MouseButtons.Left, 1, 0, 0, 0 );
                var mouseEventArgsEnd = new MouseEventArgs( MouseButtons.Left, 1, 10, 10, 0 );
                var mouseEventArgsMove = new MouseEventArgs( MouseButtons.None, 0, 10, 10, 0 );

                handler.HandleInputEvent( mouseEventArgsBegin, InputType.KeyDown );
                handler.HandleInputEvent( mouseEventArgsMove, InputType.MouseMove );

                handler.CtrlKeyIsPressed = true;
                handler.HandleInputEvent( mouseEventArgsEnd, InputType.KeyUp );

                _grabberMock.Verify();
                _visualManagerMock.Verify();
                _selectionHandlerMock.Verify();
                _objectMoverMock.Verify();
            }

            [Test]
            public void TestSwitchingToAddMode()
            {
                var clickedObjects = new SceneObject[] { new SceneObject() };

                _grabberMock.ExpectAndReturn( "GetObjectsAtPoint", clickedObjects, 0, 0 );
                _grabberMock.ExpectAndReturn( "GetObjectsAtPoint", clickedObjects, 0, 0 );

                _selectionHandlerMock.ExpectAndReturn( "get_Selection", new SceneSelection() );
                _selectionHandlerMock.Expect( "set_Mode", SelectionMode.Add );
                _selectionHandlerMock.Expect( "HandlePointSelection",
                    new object[] { clickedObjects } );

                _objectMoverMock.Strict = false;

                var mouseEvent = new MouseEventArgs( MouseButtons.Left, 1, 0, 0, 0 );

                MouseInputHandler handler = _createMockedInputHandler();

                handler.HandleInputEvent( mouseEvent, InputType.KeyDown );
                handler.ShiftKeyIsPressed = true;
                handler.HandleInputEvent( mouseEvent, InputType.KeyUp );

                _grabberMock.Verify();
                _visualManagerMock.Verify();
                _selectionHandlerMock.Verify();
                _objectMoverMock.Verify();
            }

            [Test]
            public void TestSwitchingToAddModeInAreaSelection()
            {
                var clickedObjects = new SceneObject[0];

                _grabberMock.ExpectAndReturn( "GetObjectsAtPoint", clickedObjects, 0, 0 );
                _grabberMock.ExpectAndReturn( "GetObjectsInArea", clickedObjects,
                    new Rectangle( 0, 0, 11, 11 ) );

                _visualManagerMock.Expect( "set_SelectionRectVisible", true );
                _visualManagerMock.Expect( "SetSelectionRect", new Rectangle( 0, 0, 11, 11 ) );
                _visualManagerMock.Expect( "set_SelectionRectVisible", false );

                _selectionHandlerMock.ExpectAndReturn( "get_Selection", new SceneSelection() );
                _selectionHandlerMock.Expect( "set_Mode", SelectionMode.Add );
                _selectionHandlerMock.Expect( "HandleAreaSelection",
                    new object[] { clickedObjects } );

                _objectMoverMock.Strict = false;

                MouseInputHandler handler = _createMockedInputHandler();
                var mouseEventArgsBegin = new MouseEventArgs( MouseButtons.Left, 1, 0, 0, 0 );
                var mouseEventArgsEnd = new MouseEventArgs( MouseButtons.Left, 1, 10, 10, 0 );
                var mouseEventArgsMove = new MouseEventArgs( MouseButtons.None, 0, 10, 10, 0 );

                handler.HandleInputEvent( mouseEventArgsBegin, InputType.KeyDown );
                handler.HandleInputEvent( mouseEventArgsMove, InputType.MouseMove );

                handler.ShiftKeyIsPressed = true;
                handler.HandleInputEvent( mouseEventArgsEnd, InputType.KeyUp );

                _grabberMock.Verify();
                _visualManagerMock.Verify();
                _selectionHandlerMock.Verify();
                _objectMoverMock.Verify();
            }

            [Test]
            public void TestMovingObjects()
            {
                var sceneObjects = new SceneObject[] { new SceneObject() };
                var selection = new SceneSelection();
                selection.Set( sceneObjects );

                _grabberMock.ExpectAndReturn( "GetObjectsAtPoint", sceneObjects, 0, 0  );
                
                _selectionHandlerMock.ExpectAndReturn( "get_Selection", selection );
                _selectionHandlerMock.ExpectAndReturn( "get_Selection", selection );

                _objectMoverMock.ExpectAndReturn( "get_IsCurrentlyMovingObjects", false );
                _objectMoverMock.Expect( "BeginMovingObjects", 
                    (IEnumerable<SceneObject>) selection, Point.Empty );
                _objectMoverMock.Expect( "UpdateObjectPositions", new Point( 10, 5 ) );
                _objectMoverMock.ExpectAndReturn( "get_IsCurrentlyMovingObjects", true );
                _objectMoverMock.Expect( "FinishMovingObjects" );

                var inputHandler = _createMockedInputHandler();

                var mouseDownEvent = new MouseEventArgs( MouseButtons.Left, 1, 0, 0, 0 );
                var mouseMoveEvent = new MouseEventArgs( MouseButtons.Left, 1, 10, 5, 0 );
                var mouseUpEvent = new MouseEventArgs( MouseButtons.Left, 1, 10, 5, 0 );

                inputHandler.HandleInputEvent( mouseDownEvent, InputType.KeyDown );
                inputHandler.HandleInputEvent( mouseMoveEvent, InputType.MouseMove );
                inputHandler.HandleInputEvent( mouseUpEvent, InputType.KeyUp );


                _grabberMock.Verify();
                _selectionHandlerMock.Verify();
                _visualManagerMock.Verify();
                _objectMoverMock.Verify();
            }

            private MouseInputHandler _createMockedInputHandler()
            {
                return new MouseInputHandler(
                    (ISelectionHandler) _selectionHandlerMock.MockInstance,
                    (ISceneGrabber) _grabberMock.MockInstance,
                    (ISelectionRectManager) _visualManagerMock.MockInstance,
                    (IObjectMover) _objectMoverMock.MockInstance );
            }
        }
        #endif
    }
}
